package 第七周.experiment;

import static java.lang.StrictMath.round;
import static java.lang.StrictMath.sqrt;

public class Complex {
    // 定义属性并生成getter,setter
    private double R;
    private double I;

    // 定义构造函数.
    public Complex(double R, double I) {
        this.R = R;
        this.I = I;
    }

    public double getR() {
        return R;
    }
    public double getI() {
        return I;
    }

    public boolean equals(Complex a){
            boolean result = false;
            if(R == a.R && I == a.I)
                result = true;
            return result;
    }
    //定义公有方法:加减乘除.
    public Complex ComplexAdd(Complex a) {
        double r = a.getR()+this.R;
        double i = a.getI()+this.I;
        return new Complex(r,i);
    }

    public Complex ComplexSub(Complex a) {
        double r = this.R-a.getR();
        double i = this.I-a.getI();
        return new Complex(r,i);
    }

    public Complex ComplexMulti(Complex a) {
        double r = R*a.R-I*a.I;
        double i = R*a.I-I*a.R;
        return new Complex(R * a.R - I * a.I, R * a.I + I * a.R);
    }

    public Complex ComplexDiv(Complex a) {
        double d =sqrt(a.R * a.R) + sqrt(a.I * a.I);
        double e = (R * a.I - I * a.R);
        return new Complex((R * a.R + I * a.I) / d, round(e / d));
    }

    public String toString() {
        String result = "";
        if (I == 0.0)
            result = R+"";
        else if (R == 0.0)
            result = I + "i";
        else
            if(I>0.0)
              result = R +""+ "+" + I + "i";
            else
                result=R+""+I+"i";
        return result;
    }
}
